from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponsePermanentRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from models import *
from forms import *

def view(request, path):
    pages = Page.objects.filter(name=path)
    if len(pages) == 0:
        return HttpResponsePermanentRedirect(reverse('wiki_add', kwargs={'path':path}))
    page = Page.objects.get(name=path)
    return render_to_response('wiki/view.html', {'page':page}, context_instance=RequestContext(request))

def list(request):
    pages = Page.objects.all()
    return render_to_response('wiki/list.html', {'pages':pages}, context_instance=RequestContext(request))

@login_required
def edit(request, path):
    if request.method == "POST":
        form = PageForm(request.POST)
        if form.is_valid():
            page = form.save(commit=False)
            page.name = path
            page.last_editor = request.user
            page.save()
            return HttpResponsePermanentRedirect(reverse('wiki_view', kwargs={'path':path}))
    else:
        pages = Page.objects.filter(name=path)
        if len(pages) == 0:
            return HttpResponsePermanentRedirect(reverse('wiki_add', kwargs={'path':path}))
        page = Page.objects.get(name=path)
        form = PageForm(instance=page)
        return render_to_response('wiki/edit.html', {'page':page, 'form':form}, context_instance=RequestContext(request))

@login_required
def add(request, path):
    if request.method == "POST":
        form = PageForm(request.POST)
        if form.is_valid():
            page = form.save(commit=False)
            page.name = path
            page.last_editor = request.user
            page.save()
            return HttpResponsePermanentRedirect(reverse('wiki_view', kwargs={'path':path}))
    else:
        form = PageForm()
        return render_to_response('wiki/add.html', {'path':path, 'form':form}, context_instance=RequestContext(request))
